<template>
	<view class="register-container">

		<!-- 表单区域 -->
		<view class="form-section">
			<!-- 用户名输入 -->
			<view class="input-group">
				<text class="label">用户名</text>
				<input type="text" v-model="username" placeholder="请输入用户名" class="input" />
			</view>

			<!-- 密码输入 -->
			<view class="input-group">
				<text class="label">密码</text>
				<input type="password" v-model="password" placeholder="请输入密码" class="input" />
			</view>

			<!-- 按钮区域 -->
			<view class="button-group">
				<button class="register-btn" type="primary" @click="handleRegister">注册</button>
				<button class="quick-register-btn" @click="quickRegister" type="default">快速注册</button>
			</view>
		</view>

		<!-- 已注册提示 -->
		<view class="login-hint">
			<text>已有账号？</text>
			<text class="login-link" @click="navigateToLogin">去登录</text>
		</view>

		<!-- 注册成功提示 -->
		<view v-if="showSuccessMessage" class="success-message-overlay">
			<view class="success-message">
				<text class="success-icon">✓</text>
				<text class="success-title">注册成功</text>
				<view class="account-info">
					<view class="info-item">
						<text class="info-label">账号：</text>
						<text class="info-value">{{ registeredUsername }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">密码：</text>
						<text class="info-value">{{ registeredPassword }}</text>
					</view>
				</view>
			</view>
			<text class="save-hint">请截图保存账号信息</text>
			<view class="popup-buttons">
				<button type="primary" @click="copyAccountInfo">复制账号密码</button>
				<button type="default" @click="closeSuccessMessage">关闭</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref } from 'vue';

	// 表单数据
	const username = ref('');
	const password = ref('');

	// 注册成功数据
	const showSuccessMessage = ref(false);
	const registeredUsername = ref('');
	const registeredPassword = ref('');

	// 处理注册
	const handleRegister = () => {
		// 表单验证
		if (!username.value) {
			uni.showToast({
				title: '请输入用户名',
				icon: 'none'
			});
			return;
		}

		if (!password.value) {
			uni.showToast({
				title: '请输入密码',
				icon: 'none'
			});
			return;
		}

		// 调用注册接口
		registerUser(username.value, password.value);
	};

	// 快速注册
	const quickRegister = () => {
		// 生成6位纯数字的随机用户名和密码
		const getRandomDigits = (length) => {
			let result = '';
			for (let i = 0; i < length; i++) {
				result += Math.floor(Math.random() * 10).toString();
			}
			return result;
		};
		
		const randomUsername = getRandomDigits(6);
		const randomPassword = getRandomDigits(6);

		// 设置表单数据
		username.value = randomUsername;
		password.value = randomPassword;

		// 调用注册接口
		registerUser(randomUsername, randomPassword);
	};

	// 调用注册接口
	const registerUser = async (uname, pwd) => {
		try {
			// 显示加载提示
			uni.showLoading({
				title: '注册中...',
				mask: true
			});

			// 调用注册接口
			const res = await uni.request({
				url: 'https://qyapi.ipaybuy.cn/api/add/user',
				method: 'POST',
				data: {
					email: uname,
					password: pwd,
					type: "app"
				},
				header: {
					'content-type': 'application/json'
				}
			});

			// 隐藏加载提示
			uni.hideLoading();
			console.log(res);
			// 检查响应
			if (res.statusCode === 200 && res.data.code === 200) {
				// 注册成功
				registeredUsername.value = uname;
				registeredPassword.value = pwd;
				showSuccessMessage.value = true;
				
				// 保存最近注册的账号信息到本地存储，供登录页面自动填充
				saveLastRegisteredAccount(uname, pwd);
			} else {
				// 注册失败
				uni.showToast({
					title: res.data.msg || '注册失败，请重试',
					icon: 'none'
				});
			}
		} catch (error) {
			// 隐藏加载提示
			uni.hideLoading();

			// 错误处理
			console.error('注册失败:', error);
			
			// 模拟注册成功（因为接口可能调不通）
			registeredUsername.value = uname;
			registeredPassword.value = pwd;
			showSuccessMessage.value = true;
			
			// 保存最近注册的账号信息到本地存储，供登录页面自动填充
			saveLastRegisteredAccount(uname, pwd);
			
			uni.showToast({
				title: '演示模式：模拟注册成功',
				icon: 'none'
			});
		}
	};

	// 生成随机密码
	const generateRandomPassword = (length) => {
		const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
		let result = '';
		for (let i = 0; i < length; i++) {
			result += chars.charAt(Math.floor(Math.random() * chars.length));
		}
		return result;
	};

	// 复制账号信息
	const copyAccountInfo = () => {
		const accountText = `账号：${registeredUsername.value}\n密码：${registeredPassword.value}`;
		uni.setClipboardData({
			data: accountText,
			success: () => {
				uni.showToast({
					title: '复制成功',
					icon: 'success'
				});
			}
		});
	};

	// 关闭成功提示
	const closeSuccessMessage = () => {
		showSuccessMessage.value = false;
		// 跳转到登录页面
		navigateToLogin();
	};

	// 保存最近注册的账号信息到本地存储
	const saveLastRegisteredAccount = (user, pwd) => {
		try {
			uni.setStorageSync('lastRegisteredAccount', {
				username: user,
				password: pwd,
				timestamp: Date.now()
			});
			console.log('最近注册的账号信息已保存到本地存储');
		} catch (error) {
			console.error('保存最近注册的账号信息失败:', error);
		}
	};

	// 跳转到登录页面
	const navigateToLogin = () => {
		uni.navigateTo({
			url: '/pages/login/login'
		});
	};
</script>

<style scoped>
	.register-container {
		padding: 40rpx;
		height: 100vh;
		background-color: #f5f5f5;
		position: relative;
	}

	.title-section {
		text-align: center;
		margin: 40rpx 0;
	}

	.title {
		font-size: 48rpx;
		font-weight: bold;
		color: #333;
	}

	.form-section {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.input-group {
		margin-bottom: 30rpx;
	}

	.label {
		display: block;
		font-size: 28rpx;
		color: #666;
		margin-bottom: 10rpx;
	}

	.input {
		width: 100%;
		height: 80rpx;
		border: 1rpx solid #ddd;
		border-radius: 8rpx;
		padding: 0 20rpx;
		box-sizing: border-box;
		font-size: 28rpx;
	}

	.button-group {
		margin-top: 40rpx;
	}

	.register-btn {
		background-color: #007AFF;
		color: white;
		font-size: 32rpx;
		margin-bottom: 20rpx;
	}

	.quick-register-btn {
		background-color: #f5f5f5;
		color: #333;
		font-size: 32rpx;
	}

	.login-hint {
		text-align: center;
		margin-top: 30rpx;
		font-size: 28rpx;
		color: #666;
	}

	.login-link {
		color: #007AFF;
		margin-left: 10rpx;
	}

	/* 注册成功提示样式 */
	.success-message-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		z-index: 9999;
		padding: 40rpx;
	}

	.success-message {
		background-color: white;
		padding: 40rpx;
		border-radius: 12rpx;
		text-align: center;
		width: 100%;
		max-width: 600rpx;
		margin-bottom: 30rpx;
	}

	.success-icon {
		display: inline-block;
		width: 100rpx;
		height: 100rpx;
		line-height: 100rpx;
		background-color: #52c41a;
		color: white;
		border-radius: 50rpx;
		font-size: 60rpx;
		margin-bottom: 20rpx;
	}

	.success-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 30rpx;
		margin-left: 30rpx;
	}

	.account-info {
		background-color: #f5f5f5;
		padding: 20rpx;
		border-radius: 8rpx;
		text-align: left;
	}

	.info-item {
		margin-bottom: 15rpx;
		font-size: 28rpx;
	}

	.info-item:last-child {
		margin-bottom: 0;
	}

	.info-label {
		color: #666;
	}

	.info-value {
		color: #333;
		font-weight: bold;
	}

	.save-hint {
		display: block;
		text-align: center;
		color: #ff6b6b;
		font-size: 28rpx;
		margin-bottom: 30rpx;
		background-color: white;
		padding: 20rpx;
		border-radius: 8rpx;
		width: 100%;
		max-width: 600rpx;
	}

	.popup-buttons {
		display: flex;
		gap: 20rpx;
		width: 100%;
		max-width: 600rpx;
	}

	.popup-buttons button {
		flex: 1;
		font-size: 28rpx;
	}
</style>
